package com.sunyzc.ebaotech.ybt.simulator;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sunyzc.ebaotech.ybt.simulator.abc.ABCProcessor;
import com.sunyzc.ebaotech.ybt.simulator.util.IOUtil;

public class SocketServer implements Runnable {
	private static final Logger log = LoggerFactory.getLogger(SocketServer.class);
	private final static int SERVER_PORT = 9090;
	private Socket socket;

	public static void main(String[] args) throws IOException {
		ServerSocket serverSocket = null;
		try {
			serverSocket = new ServerSocket(SERVER_PORT);
			log.info("Server started");
			while (true)
				new Thread(new SocketServer(serverSocket.accept())).start();
		} finally {
			IOUtil.closeQuietly(serverSocket);
		}
	}

	public SocketServer(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			log.info("New socket: " + socket + " start --------------------------------------");
			inputStream = new BufferedInputStream(socket.getInputStream());
			outputStream = new BufferedOutputStream(socket.getOutputStream());
			IProcessor processor = new ABCProcessor();
			String transType = "****";

			String requestHeadContentStr = processor.readHeadConetentStr(transType, inputStream);
			String requestBodyContentStr = processor.readBodyConetentStr(transType, inputStream, requestHeadContentStr);
			log.info("Request Head: " + requestHeadContentStr);
			log.info("Request Body: " + requestBodyContentStr);

			byte[] responseBodyContentBytes = processor.generateResponseBodyBytes(transType);
			byte[] responseHeadContentBytes = processor.generateHeadBytes(transType, responseBodyContentBytes);
			log.info("response Head: " + processor.convertContentBytesToStr(responseHeadContentBytes));
			log.info("response Body: " + processor.convertContentBytesToStr(responseBodyContentBytes));
			outputStream.write(responseHeadContentBytes);
			outputStream.write(responseBodyContentBytes);
			outputStream.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtil.closeQuietly(inputStream);
			IOUtil.closeQuietly(outputStream);
			IOUtil.closeQuietly(socket);
			log.info("Socket: " + socket + " end --------------------------------------");
		}
	}
}